<?php
namespace app\store\model;
use app\common\model\GoodsGroup as GoodsGroupModel;
use think\Db;

/**
 * 拼团商品模型
 */
class GoodsGroup extends GoodsGroupModel
{
    /**
     * 添加
     */
    public function add(array $data,$shop_id)
    {
		$data['shop_id'] = $shop_id;
        $data['wxapp_id'] = self::$wxapp_id;
        // 开启事务
        Db::startTrans();
        try {
            // 添加商品
            $this->allowField(true)->save($data);
            // 修改商品规格
            $this->updateGoodsSpec($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;	
    }

    /**
     * 编辑
     */
    public function edit($data)
    {
        // 开启事务
        Db::startTrans();
        try {
            // 添加商品
            $this->allowField(true)->save($data);
            // 修改商品规格
            $this->updateGoodsSpec($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 修改商品规格
     */
    private function updateGoodsSpec($data)
    {
        //多规格
        if(isset($data['spec_many'])){
            for($n=0;$n<sizeof($data['spec_many']['spec_list']);$n++){
                $model = (new GoodsSpec)->where([
                    'goods_id' => $data['goods_id'],
                    'spec_sku_id' => $data['spec_many']['spec_list'][$n]['spec_sku_id']
                ])->find();
                $model->group_price = $data['spec_many']['spec_list'][$n]['form']['group_price'];
                $model->group_stock_num = $data['spec_many']['spec_list'][$n]['form']['group_stock_num'];
                $model->save();
            }
            return true;
        }
        //单规格
        $model = (new GoodsSpec)->where([
            'goods_id' => $data['goods_id']
        ])->find();
        $model->group_price = $data['spec']['group_price'];
        $model->group_stock_num = $data['spec']['group_stock_num'];
        $model->save();
        return true;
    }

    /**
     * 删除
     */
    public function remove()
    {
        return $this->delete(); 
        
    }

}
